<template>
  <div>
    <el-form :inline="true" style="height: 30px" @submit.native.prevent>
      <el-form-item>
        <product-series-cascade @change="productChange" />
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="deviceName"
          clearable
          :placeholder="$t('device')+$t('name')"
          @change="searchNameChange"
        />
      </el-form-item>
      <el-form-item>
        <el-select v-model="status" @change="statusChange">
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <el-table
      ref="multipleTable"
      :data="deviceList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      @cell-click="getSensor"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        :label="$t('device')+$t('name')"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.deviceName }}({{ scope.row.deviceCore }})</span>
        </template>
      </el-table-column>
      <el-table-column  :label="$t('surplus')" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.surplus }}%</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" :label="$t('status')"  width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status=='ONLINE'?'success':'danger'">{{ formatDeviceStatus(scope.row) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column  width="150">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            @click.stop="edit(scope.row)"
          >{{ $t('info') }}
          </el-button>
          <el-button
            type="text"
            icon="el-icon-s-tools"
            @click.stop="deviceSetting(scope.row)"
          >{{ $t('setting') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: right;margin: 15px 0">
      <el-pagination
        background
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total,sizes,prev,pager,next,jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      :visible.sync="showSetting"
      :title="device.deviceName"
      append-to-body
      width="1200px"
      top="15px"
    >
      <device-setting
        :device-core="device.deviceCore"
        class="uni-scroll"
        style="height: 600px"
      />
    </el-dialog>

    <el-drawer
      append-to-body
      size="70%"
      :visible.sync="drawer"
      direction="rtl"
    >
      <div class="box-card" style="height: calc(100vh - 92px)">
        <div
          class="uni-scroll"
          style="height: calc(100vh - 100px)"
        >
          <sensor-camera-list :device="device" />
        </div>
      </div>
    </el-drawer>

  </div>
</template>

<script>
import DeviceSetting from '@/components/DeviceSetting'
import SensorCameraList from '@/components/SensorCameraList'
import ProductSeriesCascade from '@/components/ProductSeriesCascade'
import {
  pageGetDevice,
  deleteBelong,
  updateBelong
} from '@/api/iot/iotDeviceBelongApi'
import {
  formatDate,
  successNotice,
  formatDeviceStatus,
  listDeviceStatus
} from '@/util/common'
import {
  getPageSize,
  setPageSize
} from '@/util/storage'
export default {
  name: 'UserDeviceChoice',
  components: {
    ProductSeriesCascade,
    DeviceSetting,
    SensorCameraList
  },
  props: {
    userId: {
      type: Number,
      default: null
    },
    groupId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      showSetting: false,
      drawer: false,
      deviceList: [],
      currentPage: 1,
      total: 0,
      pageSize: getPageSize(),
      deviceName: null,
      statusList: [],
      status: null,
      productId: null,
      seriesId: null,
      openChose: false,
      device: {}
    }
  },
  watch: {
    groupId: {
      deep: true,
      handler(val) {
        this.pageGetDevice()
      }
    }
  },
  created() {
    this.statusList = listDeviceStatus(this)
    if (this.userId != null) {
      this.pageGetDevice()
    }
  }, methods: {
    getSensor(item) {
      this.device = item
      this.drawer = true
    },
    deviceSetting(item, index) {
      this.device = item
      this.showSetting = true
    },
    handleSelectionChange(list) {
      if (!this.openChose) {
        return
      }
      for (let i = 0; i < list.length; i++) {
        const item = list[i]
        let have = false
        for (let j = 0; j < this.choseDevicBelongIdList.length; j++) {
          const deviceBelongId = this.choseDevicBelongIdList[j]
          if (deviceBelongId === item.deviceBelongId) {
            have = true
            break
          }
        }
        if (!have) {
          updateBelong({
            groupId: this.groupId,
            deviceBelongId: item.deviceBelongId
          }).then(res => {
            successNotice(this)
            this.choseDevicBelongIdList.push(item.deviceBelongId)
          })
        }
      }

      for (let j = 0; j < this.choseDevicBelongIdList.length; j++) {
        const deviceBelongId = this.choseDevicBelongIdList[j]
        let have = false
        for (let i = 0; i < list.length; i++) {
          const item = list[i]
          if (deviceBelongId === item.deviceBelongId) {
            have = true
            break
          }
        }
        if (!have) {
          updateBelong({
            groupId: 0,
            deviceBelongId: deviceBelongId
          }).then(res => {
            successNotice(this)
            for (let i = 0; i < this.choseDevicBelongIdList.length; i++) {
              if (this.choseDevicBelongIdList[i] === deviceBelongId) {
                this.choseDevicBelongIdList.splice(i, 1)
                break
              }
            }
          })
        }
      }
    },
    searchNameChange() {
      this.currentPage = 0
      this.pageGetDevice()
    },
    statusChange() {
      this.currentPage = 1
      this.pageGetDevice()
    },
    provinceCityChange(item) {
      this.provinceId = item.provinceId
      this.cityId = item.cityId
      this.currentPage = 1
      this.pageGetDevice()
    },
    productChange(val) {
      this.productId = val.productId
      this.seriesId = val.seriesId
      this.currentPage = 1
      this.pageGetDevice()
    },
    formatDeviceStatus(item) {
      return formatDeviceStatus(this, item.status)
    },
    deleteBelong(item) {
      const that = this
      this.$confirm(this.$t('delete') + item.deviceName, {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteBelong({
            deviceBelongId: item.deviceBelongId
          }).then(res => {
            const { code } = res
            if (code === '200') {
              successNotice(that)
            }
            that.pageGetDevice()
          })
        })
    },
    edit(item) {
      this.device = item
      this.$router.push({
        path: '/device/manage/' + item.deviceCore,
        query: { deviceCore: item.deviceCore, deviceName: item.deviceName }
      })
    },
    formatDate(data) {
      return formatDate(this, data)
    },
    handleSizeChange(val) {
      this.pageSize = val
      setPageSize(this.pageSize)
      this.pageGetDevice()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.pageGetDevice()
    },
    pageGetDevice() {
      this.openChose = false
      pageGetDevice({
        pageSize: this.pageSize,
        status: this.status,
        deviceName: this.deviceName,
        currentPage: this.currentPage,
        userId: this.userId,
        productId: this.productId,
        seriesId: this.seriesId,
        deviceIdDesc: true
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.total = data.total
          this.deviceList = data.data
          const that = this
          this.$nextTick(() => {
            const choseDevicBelongIdList = []
            that.deviceList.forEach(device => {
              if (device.groupId === that.groupId) {
                choseDevicBelongIdList.push(device.deviceBelongId)
                that.$refs.multipleTable.toggleRowSelection(device)
              }
            })
            that.choseDevicBelongIdList = choseDevicBelongIdList
            setTimeout(() => {
              that.openChose = true
            }, 1500)
          })
        }
      })
    }
  }

}
</script>

